package learn.up.java.md;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;


/**
 * 消息摘要算法  messageDigest
 * MAC: Message Authentication Code   消息摘要算法
 * HMAC: Key-Hashed Message Authentication Code 含密钥的消息摘要算法
 * 
 * 应用：SecureCRT
 * JDK没有提供md4的实现
 * @author Administrator
 *
 */
public class Md5 {
	
	// 全局数组
    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	private static String str = "john";

	public static void main(String[] args) throws UnsupportedEncodingException {
		jdkMD5();
		commonsUtilMD5();
	}
	
	public static void jdkMD5() {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			/*
			 * 得到二进制的字节数组
			 */
			byte[] data = md.digest(str.getBytes("utf-8"));
			/*
			 * 把byte数组转换成16进制，可以自己写实现，或者用第三方工具
			 */
			StringBuffer sb=new StringBuffer();
			for (int i = 0; i < data.length; i++) {
				int b = data[i];
				if (b < 0)
					b += 256; 
				sb.append(strDigits[b / 16] + strDigits[b % 16]);
			}
			System.out.println("自定义实现："+sb);
			System.out.println("commons-codec工具："+Hex.encodeHexString(data));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void commonsUtilMD5() throws UnsupportedEncodingException {
		System.out.println("DigestUtil: "+DigestUtils.md5Hex(str.getBytes("utf-8")));
		
	}
	
}
